Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




index( ) FUNCTION


index( ) Function


The index( ) Function is used to find the starting position of the substring.


Note : The index( ) Function is exactly similar to the find( ) method, the only difference is, the find( ) Function returns -1 if the value is not found.

Example :


x = "Hello Beautiful World"
y = x.index("Beautiful")
print("The substring is located at the position ",y)


Output :



  The substring is located at the position 6

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x = "Hello Beautiful World"

java_Collections

And we would be searching the substring 'Beautiful', from the String, 'Hello Beautiful World'.


So, we have used the 'index( )' Function to find the substring 'Beautiful'.


y = x.find("Beautiful")

And what 'index( )' Function does is, goes to the String 'Hello Beautiful World' and searches for the position of the substring 'Beautiful'.


java_Collections

And finds the substring 'Beautiful' in the 6th position. And the position (i.e. '6') is stored in variable 'y'.


java_Collections

And thus prints the position.


print("The substring is located at the position ",y)

Output :



  The substring is located at the position 6

Now, let us say you have the below String,


"The Beautiful world is Beautiful indeed"

And you have to search for the second occurrence of 'Beautiful'.


To solve this, you can add a second and a third parameter used by 'index( )' function that tells the range, and in between the range the substring can be checked.


Let us see with the below example.


Example :


x = "The Beautiful world is Beautiful indeed"
y = x.index("Beautiful", 20, 35)
print("The substring is located at the position ",y)


Output :



  The substring is located at the position 23

So, if you see the above output, only the second occurrence of 'Beautiful' is searched for.


That is because of the below line,


y = x.index("Beautiful", 20, 35)

Where we have specified the the range as '20' and '35', in second and third parameter.


Which says that search for the substring 'Beautiful' in the positions between '20' to '35'.


And thus we got the position as '23' assigned to the variable 'y',


java_Collections